package org.orz.cloud.auth;

import cn.hutool.core.util.StrUtil;
import org.orz.cloud.common.exception.BusinessException;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static org.orz.cloud.auth.AuthConstants.HEADER_WORKBENCH;

public class ServiceContextUtil {

    public static String getWorkbenchWithExistCheck(){
        String workbench = getWorkbench();
        if(StrUtil.isBlank(workbench)){
            throw new BusinessException(AuthErrorEnum.WORKBENCH_IS_NULL);
        }
        return workbench;
    }

    public static String getWorkbench(){
        RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
        if(!(attributes instanceof ServletRequestAttributes)){
            return null;
        }
        HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
        return request.getHeader(HEADER_WORKBENCH);
    }

}
